/*
 * SearchDate.java Copyright 2004 Paul Mukherjee
 */
package org.nanhill.support.hibernate.search.demo.filesearch;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author pmu
 * @version $Revision: 1.2 $
 * 
 * Abstract base class for date-relates search criteria.
 */
public abstract class SearchDate extends VolumeSearchCriterion {

	/**
	 * The format to be used for dates. This format must be adhered to when
	 * creating instances.
	 */
	private static final String DATE_FORMAT = "yyyy-MM-dd";

	/**
	 * The date represented by this search criterion.
	 */
	private Date date;

	/**
	 * Creates an instance of this class.
	 * 
	 */
	public SearchDate() {
	}

	/**
	 * @return Returns the day.
	 */
	public String getDay() {
		return new SimpleDateFormat("dd").format(date);
	}

	/**
	 * @return Returns the month.
	 */
	public String getMonth() {
		return new SimpleDateFormat("MM").format(date);
	}

	/**
	 * @return Returns the year.
	 */
	public String getYear() {
		return new SimpleDateFormat("yyyy").format(date);
	}

	/**
	 * Sets the value of the date. There are three possibilities:
	 * <ul>
	 * <li> The value has four characters yyyy representing the year.
	 * <li> The value has seven characters yyyy-mm representing year and month
	 * separated by a '-'
	 * <li> The value has ten characters yyyy-mm-dd representing year, month and
	 * day, separated by '-'
	 * </ul>
	 * 
	 * @param value
	 *            The value to parse
	 * @throws ParseException
	 *             if the value does not conform to the above convention.
	 */
	public void setValue(String value) throws ParseException {
		DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
		if (value.length() == 4) {
			value += "-" + getDefaultMonth();
		}

		if (value.length() == 7) {
			value += "-" + getDefaultDay();
		}
		date = dateFormat.parse(value);
	}

	/**
	 * @return Returns the date specified by this criterion.
	 */
	public Date getValue() {
		return date;
	}

	/**
	 * @return Returns a string representing the default day for this search
	 *         criterion.
	 */
	protected abstract String getDefaultDay();

	/**
	 * @return Returns a string representing the default month for this
	 *         criterion.
	 */
	protected abstract String getDefaultMonth();
}
